import request from "@/utils/request";

const FileAPI = {
  /**
   * 上传文件
   *
   * @param formData
   * @param provider 云服务提供商 (qiniu, aliyun, minio)
   */
  upload(formData, provider = "qiniu") {
    const data = new FormData();
    // 如果传入的是FormData，直接使用；否则创建新的FormData
    if (formData instanceof FormData) {
      data.append("file", formData.get("file"));
    } else {
      data.append("file", formData);
    }
    data.append("provider", provider);
    
    return request({
      url: "/admin/file/upload",
      method: "post",
      data: data,
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
  },

  /**
   * 上传文件
   * @param file 文件对象
   * @param provider 云服务提供商 (qiniu, aliyun, minio)
   */
  uploadFile(file, provider = "qiniu") {
    const formData = new FormData();
    formData.append("file", file);
    formData.append("provider", provider);
    
    console.log('发送的文件:', file);
    console.log('发送的provider:', provider);
    
    return request({
      url: "/admin/file/upload",
      method: "post",
      data: formData,
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
  },

  /**
   * 删除文件
   *
   * @param filePath 文件完整路径
   */
  delete(filePath) {
    return request({
      url: "/api/v1/files",
      method: "delete",
      params: { filePath: filePath },
    });
  },

  /**
   * 下载文件
   * @param url
   * @param fileName
   */
  download(url, fileName) {
    return request({
      url: url,
      method: "get",
      responseType: "blob",
    }).then((res) => {
      const blob = new Blob([res.data]);
      const a = document.createElement("a");
      const url = window.URL.createObjectURL(blob);
      a.href = url;
      a.download = fileName || "下载文件";
      a.click();
      window.URL.revokeObjectURL(url);
    });
  },
};

export default FileAPI; 